#include "common.h"
#include "messagetype.h"
#include "networkessential.h"
#include "messageMemberList.h"

#include <iostream>
using namespace std;

messageMemberList::messageMemberList(const std::string &groupname, 
									 std::map<std::string, u_long> &member_list)
:messageBase(NET_MESSAGE_MEMBER_LIST),
 m_member_list(member_list),
 m_groupname(groupname)
{
}

void messageMemberList::generateMessage(std::string &buf) const
{
	// Message content:
	// messagetype messageheader_len groupname_len groupname 
	// membercount membername_len1 membername1 in_addr ... ...

	unsigned int messagetype = m_messagetype;
	int message_len;
	int groupname_len  = m_groupname.size();

	cout << "Group name: " << m_groupname << endl;
	message_len = groupname_len + IntLength * 2;

	std::map<std::string, u_long>::const_iterator it = m_member_list.begin();
	for (; it != m_member_list.end(); it++)
	{
		int membername_len = it->first.size();
		message_len += (membername_len + IntLength * 2);
	}

	buf.append(FourBytesToNetChar(messagetype), IntLength);
	buf.append(FourBytesToNetChar(message_len), IntLength);
	buf.append(FourBytesToNetChar(groupname_len), IntLength);
	buf.append(m_groupname);
	
	int membercount = m_member_list.size();
	buf.append(FourBytesToNetChar(membercount), IntLength);

	it = m_member_list.begin();
	for (; it != m_member_list.end(); it++)
	{
		int membername_len = it->first.size();
		u_long addr = it->second;
		buf.append(FourBytesToNetChar(membername_len), IntLength);
		buf.append(it->first);
		buf.append(FourBytesToNetChar(addr), IntLength);
	}
}
